//
//  SY_AttendanceAccountViewController.m
//  ChatDemo-UI2.0
//
//  Created by Sylar on 2017/2/13.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "SY_AttendanceAccountViewController.h"
#import "FDCalendar.h"
#import "SY_Today_AttendanceViewController.h"

@interface SY_AttendanceAccountViewController ()<FDCalendarDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UIAlertViewDelegate>
{
    UIControl *control;
    
    NSString *thisYear;
    NSString *thisMonth;
    
    NSString *selectYearStr;
    
}

@property (nonatomic, strong) UIScrollView *bgScrollView;
@property (nonatomic, strong) UIButton *classBtn;
@property (nonatomic, strong) UIButton *dateBtn;
@property (nonatomic, strong) UIPickerView *classPicker;
@property (nonatomic, strong) UIPickerView *datePicker;
@property (nonatomic, strong) FDCalendar  *calender;
@property (nonatomic, strong) UILabel *quanqinlvLabel;
@property (nonatomic, strong) UILabel *quanqinLabel;
@property (nonatomic, strong) UILabel *weiquanqinLabel;
@property (nonatomic, strong) UILabel *wujiluLabel;

@property (nonatomic, strong) NSDictionary *classInfoDic;
@property (nonatomic, copy)   NSString  *classid;
@property (nonatomic, strong) NSMutableArray *classNames; //存放班级名称
@property (nonatomic, strong) NSMutableArray *classesArr; //存放班级
@property (nonatomic,assign)  NSInteger indexOfType;
@property (nonatomic, copy)   NSString *dateString;

@end

@implementation SY_AttendanceAccountViewController

- (void)loadView {
    
    [super loadView];
    
    self.navBar.nav_titleLabel.text = @"考勤统计";
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    NSDateFormatter *formatter1 =[[NSDateFormatter alloc]init];
    [formatter1 setDateFormat:@"yyyy-MM"];
    self.dateString = [formatter1 stringFromDate:[NSDate date]];
    
    NSDateFormatter *formmater = [[NSDateFormatter alloc] init];
    [formmater setDateFormat:@"yyyy-MM-dd"];
    
    thisYear = [[formmater stringFromDate:[NSDate date]] componentsSeparatedByString:@"-"][0];
    thisMonth = [[formmater stringFromDate:[NSDate date]] componentsSeparatedByString:@"-"][1];
    selectYearStr = [[formmater stringFromDate:[NSDate date]] componentsSeparatedByString:@"-"][0];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.bgScrollView];
    
    [self setTopView];
    
    [self loadAllClassData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Method

- (void)setTopView {
    
    UILabel *classLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 12, 62, 26)];
    classLabel.textColor = colorFromHex(@"#3b3b3b");
    classLabel.font = [UIFont systemFontOfSize:15];
    classLabel.text = @"选择班级";
    [self.bgScrollView addSubview:classLabel];
    
    self.classBtn.x = classLabel.right + 5;
    [self.bgScrollView addSubview:self.classBtn];
    
    self.dateBtn.x = SCREENWIDTH - 15 - 92;
    [self.bgScrollView addSubview:self.dateBtn];
    
    UILabel *dateLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.dateBtn.x - 5 -62, 12, 62, 26)];
    dateLabel.textColor = colorFromHex(@"#3b3b3b");
    dateLabel.font = [UIFont systemFontOfSize:15];
    dateLabel.text = @"选择日期";
    [self.bgScrollView addSubview:dateLabel];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, self.dateBtn.bottom+12, SCREENWIDTH, 10)];
    [lineView setBackgroundColor:colorFromHex(@"#F5F8FA")];
    [self.bgScrollView addSubview:lineView];
    
    self.calender = [[FDCalendar alloc]initWithCurrentDate:[NSDate date]];
    self.calender.delegete = self;
    self.calender.today = [NSDate date];
    self.calender.frame = CGRectMake(0, lineView.bottom, self.view.frame.size.width, 352);
    [self.bgScrollView addSubview:self.calender];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(15, self.calender.bottom, SCREENWIDTH, 0.5)];
    [line setBackgroundColor:colorFromHex(@"#DEDEDE")];
    [self.bgScrollView addSubview:line];
    
    
    UILabel *defautLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(30, line.bottom+23, 64, 15)];
    defautLabel1.text = @"全勤率：";
    defautLabel1.textColor = colorFromHex(@"#3b3b3b");
    defautLabel1.font = [UIFont systemFontOfSize:15];
    [self.bgScrollView addSubview:defautLabel1];
    
    self.quanqinlvLabel = [[UILabel alloc]initWithFrame:CGRectMake(defautLabel1.right, line.bottom+21, 60, 19)];
    self.quanqinlvLabel.textColor = colorFromHex(@"#3b3b3b");
    self.quanqinlvLabel.font = [UIFont systemFontOfSize:19];
    [self.bgScrollView addSubview:self.quanqinlvLabel];
    
    UILabel *defautLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(30, self.quanqinlvLabel.bottom+15, 64, 15)];
    defautLabel2.text = @"未全勤：";
    defautLabel2.textColor = colorFromHex(@"#3b3b3b");
    defautLabel2.font = [UIFont systemFontOfSize:15];
    [self.bgScrollView addSubview:defautLabel2];
    
    self.weiquanqinLabel = [[UILabel alloc]initWithFrame:CGRectMake(defautLabel2.right, self.quanqinlvLabel.bottom+13, 60, 19)];
    self.weiquanqinLabel.textColor = colorFromHex(@"#3b3b3b");
    self.weiquanqinLabel.font = [UIFont systemFontOfSize:19];
    [self.bgScrollView addSubview:self.weiquanqinLabel];
    
    UILabel *defautLabel3 = [[UILabel alloc]initWithFrame:CGRectMake(30+SCREENWIDTH/2, line.bottom+23, 64, 15)];
    defautLabel3.text = @"全    勤：";
    defautLabel3.textColor = colorFromHex(@"#3b3b3b");
    defautLabel3.font = [UIFont systemFontOfSize:15];
    [self.bgScrollView addSubview:defautLabel3];
    
    self.quanqinLabel = [[UILabel alloc]initWithFrame:CGRectMake(defautLabel3.right, line.bottom+21, 60, 19)];
    self.quanqinLabel.textColor = colorFromHex(@"#3b3b3b");
    self.quanqinLabel.font = [UIFont systemFontOfSize:19];
    [self.bgScrollView addSubview:self.quanqinLabel];
    
    UILabel *defautLabel4 = [[UILabel alloc]initWithFrame:CGRectMake(30+SCREENWIDTH/2, self.quanqinLabel.bottom+15, 64, 15)];
    defautLabel4.text = @"无记录：";
    defautLabel4.textColor = colorFromHex(@"#3b3b3b");
    defautLabel4.font = [UIFont systemFontOfSize:15];
    [self.bgScrollView addSubview:defautLabel4];
    
    self.wujiluLabel = [[UILabel alloc]initWithFrame:CGRectMake(defautLabel4.right, self.quanqinLabel.bottom+13, 60, 19)];
    self.wujiluLabel.textColor = colorFromHex(@"#3b3b3b");
    self.wujiluLabel.font = [UIFont systemFontOfSize:19];
    [self.bgScrollView addSubview:self.wujiluLabel];
    
}

- (void)cancelControlAction
{
    [control removeFromSuperview];
}

- (void)chooseTypeAction:(UIButton *)sender
{
    [control removeFromSuperview];
    
    if (sender.tag == 1) {
        
        [self.classesArr objectAtIndex:_indexOfType];
        
        self.classid = [NSString stringWithFormat:@"%@",[[self.classesArr objectAtIndex:_indexOfType] objectForKey:@"classid"]];
        self.classInfoDic = [self.classesArr objectAtIndex:_indexOfType];
        
        [self.classBtn setTitle:[self.classNames objectAtIndex:_indexOfType] forState:(UIControlStateNormal)];
        
        [self.calender setValue:nil forKeyPath:@"centerCalendarItem.selectedIndexPath"];
        
        [self loadRecordWithDate:self.dateString];
        
    }else if (sender.tag == 2) {
        
        [self.dateBtn setTitle:self.dateString forState:(UIControlStateNormal)];
        
        [self loadRecordWithDate:self.dateString];
        
    }
}

#pragma mark - Action

- (void)chooseClass {
    
    [control removeFromSuperview];
    control=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH)];
    control.backgroundColor=[UIColor clearColor];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH-210)];
    [bgView setBackgroundColor:[UIColor clearColor]];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelControlAction)];
    [bgView addGestureRecognizer:tap];
    [control addSubview:bgView];
    
    UIView *sureBC = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGH-210, SCREENWIDTH, 30)];
    [sureBC setBackgroundColor:[UIColor whiteColor]];
    [control addSubview:sureBC];
    
    UIButton *sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame=CGRectMake(SCREENWIDTH-12-40,SCREENHEIGH-210, 40, 40);
    [sureBtn setTitle:@"完成" forState:UIControlStateNormal];
    [sureBtn setTitleColor:RGBACOLOR(57, 173, 255, 1) forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(chooseTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    sureBtn.tag = 1;
    
    [control addSubview:sureBtn];
    
    [control addSubview:self.classPicker];
    
    UIWindow *window = KeyWindow;
    [window addSubview:control];
    
}

- (void)chooseDate {
    
    
    self.dateString = [NSString stringWithFormat:@"%@-01",thisYear];
    
    [control removeFromSuperview];
    control=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH)];
    control.backgroundColor=[UIColor clearColor];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH-210)];
    [bgView setBackgroundColor:[UIColor clearColor]];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelControlAction)];
    [bgView addGestureRecognizer:tap];
    [control addSubview:bgView];
    
    UIView *sureBC = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGH-210, SCREENWIDTH, 30)];
    [sureBC setBackgroundColor:[UIColor whiteColor]];
    [control addSubview:sureBC];
    
    UIButton *sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame=CGRectMake(SCREENWIDTH-12-40,SCREENHEIGH-210, 40, 40);
    [sureBtn setTitle:@"完成" forState:UIControlStateNormal];
    [sureBtn setTitleColor:RGBACOLOR(57, 173, 255, 1) forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(chooseTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    sureBtn.tag = 2;
    
    [control addSubview:sureBtn];
    
    [control addSubview:self.datePicker];
    
    UIWindow *window = KeyWindow;
    [window addSubview:control];
    
}

#pragma mark - PickerDelegate & PickerDataSource

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    if (pickerView == self.classPicker) {
        return 1;
    }
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    if (pickerView == self.classPicker) {
        return self.classesArr.count;
    }else if (pickerView == self.datePicker) {
        
        if (component == 0) {
            return 100;
        }else
        {
            if ([thisYear isEqualToString:selectYearStr]) {
                return [thisMonth integerValue];
            }else {
                return 12;
            }
        }
    }
    
    return 0;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (pickerView == self.classPicker) {
        return [self.classNames objectAtIndex:row];
    }else if (pickerView == self.datePicker) {
        if (component==0) {
            return [NSString stringWithFormat:@"%ld年",[thisYear intValue]-row];
        }else {
            return [NSString stringWithFormat:@"%ld月",row+1];
            
        }
    }
    
    return nil;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (pickerView == self.classPicker) {
        self.indexOfType = row;
    }else if (pickerView == self.datePicker) {
        
        NSString *monthStr;
        
        if (component == 0) {
            
            selectYearStr = [NSString stringWithFormat:@"%ld",(long)[thisYear integerValue]-[pickerView selectedRowInComponent:0]];
            
            monthStr = [pickerView selectedRowInComponent:1]+1<10?[NSString stringWithFormat:@"0%ld",(long)[pickerView selectedRowInComponent:1]+1]:[NSString stringWithFormat:@"%ld",(long)[pickerView selectedRowInComponent:1]+1];
            
            [pickerView reloadComponent:1];
            
            if ([selectYearStr isEqualToString:thisYear]) {
                [pickerView selectRow:0 inComponent:1 animated:YES];
                monthStr = @"01";
            }
            
            
        }else {
            monthStr = [pickerView selectedRowInComponent:1]+1<10?[NSString stringWithFormat:@"0%ld",(long)[pickerView selectedRowInComponent:1]+1]:[NSString stringWithFormat:@"%ld",(long)[pickerView selectedRowInComponent:1]+1];
        }
        
        self.dateString = [NSString stringWithFormat:@"%@-%@",selectYearStr,monthStr];
    }
}

-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    
    return 200;
}

#pragma mark = AlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - CalenderDelegate

-(void)didSelectedDate:(NSDate *)date
{
    NSDateFormatter *formatter1 =[[NSDateFormatter alloc]init];
    [formatter1 setDateFormat:@"yyyy-MM-dd"];
    
    NSTimeInterval  interval =-1;
    NSDate *seleceDate = [date initWithTimeInterval:interval sinceDate:date];
    
    NSString *dateString = [formatter1 stringFromDate:seleceDate];
    
    NSLog(@"选择的日期 == %@",dateString);
    
    SY_Today_AttendanceViewController *vc = [[SY_Today_AttendanceViewController alloc]init];
    vc.dateStr = dateString;
    vc.classID = self.classid;
    vc.className = [self.classNames objectAtIndex:_indexOfType];
    vc.selectDate = seleceDate;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Request

//加载班级
- (void)loadAllClassData {
    
    BaseModel *param = [BaseModel param];
    param.method = @"sy_rollcall_classlist";
    param.teacherid = USERID;
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        for (NSDictionary *dic in arr) {
            
            [self.classesArr addObject:dic];
        }
        
        if (self.classesArr.count == 0) {  //没有班级
            
            NSString *message = @"请先创建/加入班级";
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            
            alert.tag = 101;
            [alert show];
        }else if(self.classesArr.count > 0){ //有班级
            
            
            for (NSDictionary *dic in self.classesArr) {
                
                NSString *className = [dic objectForKey:@"classname"];
                
                [self.classNames addObject:className];
            }
            
            self.classid = [NSString stringWithFormat:@"%@",[[self.classesArr objectAtIndex:0] objectForKey:@"classid"]];
            self.classInfoDic = [self.classesArr objectAtIndex:0];
            
            [self.classBtn setTitle:[self.classNames firstObject] forState:(UIControlStateNormal)];
            
            [self loadRecordWithDate:self.dateString];
            
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)loadRecordWithDate:(NSString *)monDate {
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"sy_rollcall_record" forKey:@"method"];
    [dict setObject:self.classid forKey:@"classid"];
    [dict setObject:monDate forKey:@"date"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        NSDictionary *dict = (NSDictionary *)resposeJson;
        
        NSDateFormatter *formatter1 =[[NSDateFormatter alloc]init];
        [formatter1 setDateFormat:@"yyyy-MM"];
        
        self.calender.markArr = [[[dict objectForKey:@"re_data"] objectAtIndex:0] objectForKey:@"monlist"];
        
        self.calender.date = [formatter1 dateFromString:self.dateString];
        
        NSDictionary *redateDic = [[dict objectForKey:@"re_data"] objectAtIndex:0];
        
        self.quanqinLabel.text = [NSString stringWithFormat:@"%@天",[redateDic objectForKey:@"fullday"]];
        self.weiquanqinLabel.text = [NSString stringWithFormat:@"%@天",[redateDic objectForKey:@"partday"]];
        self.quanqinlvLabel.text = [NSString stringWithFormat:@"%@",[redateDic objectForKey:@"fullrate"]];
        self.wujiluLabel.text = [NSString stringWithFormat:@"%@天",[redateDic objectForKey:@"norecordday"]];
        
    } failure:^(NSInteger recode, NSError * error){
        
    }];
}



#pragma mark - Get

- (UIScrollView *)bgScrollView {
    
    if (_bgScrollView == nil) {
        _bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-64)];
        [_bgScrollView setBackgroundColor:[UIColor whiteColor]];
        _bgScrollView.showsVerticalScrollIndicator = NO;
        _bgScrollView.showsHorizontalScrollIndicator = NO;
        _bgScrollView.contentSize = CGSizeMake(SCREENWIDTH, SCREENHEIGH);
        
    }
    return _bgScrollView;
}

- (UIButton *)classBtn {
    
    if (_classBtn == nil) {
        _classBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_classBtn setFrame:CGRectMake(0, 12, 92, 26)];
        _classBtn.layer.borderWidth = 0.5;
        _classBtn.layer.cornerRadius = 4;
        _classBtn.layer.borderColor = [colorFromHex(@"#1EBFFF") CGColor];
        [_classBtn setBackgroundColor:colorFromHex(@"#E6F6FC")];
        _classBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_classBtn setTitleColor:colorFromHex(@"#1EBFFF") forState:(UIControlStateNormal)];
        [_classBtn addTarget:self action:@selector(chooseClass) forControlEvents:(UIControlEventTouchUpInside)];
        
        
    }
    return _classBtn;
}

- (UIButton *)dateBtn {
    
    if (_dateBtn == nil) {
        _dateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_dateBtn setFrame:CGRectMake(0, 12 , 92, 26)];
        _dateBtn.layer.borderWidth = 0.5;
        _dateBtn.layer.cornerRadius = 4;
        _dateBtn.layer.borderColor = [colorFromHex(@"#1EBFFF") CGColor];
        [_dateBtn setBackgroundColor:colorFromHex(@"#E6F6FC")];
        [_dateBtn setTitleColor:colorFromHex(@"#1EBFFF") forState:(UIControlStateNormal)];
        _dateBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_dateBtn addTarget:self action:@selector(chooseDate) forControlEvents:(UIControlEventTouchUpInside)];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM"];
        
        NSString *dateStr = [formatter stringFromDate:[NSDate date]];
        [_dateBtn setTitle:dateStr forState:(UIControlStateNormal)];
        
    }
    return _dateBtn;
}

- (UIPickerView *)datePicker {
    
    if (_datePicker == nil) {
        _datePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SCREENHEIGH - 170, SCREENWIDTH, 170)];
        _datePicker.delegate = self;
        _datePicker.dataSource = self;
        _datePicker.showsSelectionIndicator = NO;
        _datePicker.backgroundColor=[UIColor whiteColor];
        _datePicker.userInteractionEnabled=YES;
    }
    
    return _datePicker;
}

- (UIPickerView *)classPicker {
    
    if (_classPicker == nil) {
        _classPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SCREENHEIGH - 170, SCREENWIDTH, 170)];
        _classPicker.delegate = self;
        _classPicker.dataSource = self;
        _classPicker.showsSelectionIndicator = NO;
        _classPicker.backgroundColor=[UIColor whiteColor];
        _classPicker.userInteractionEnabled=YES;
    }
    
    return _classPicker;
}
- (NSMutableArray *)classesArr{
    
    if (_classesArr == nil) {
        
        _classesArr = [NSMutableArray array];
        _classNames = [NSMutableArray array];
    }
    
    return _classesArr;
}

@end
